package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RJx")
public class RJxController extends HttpServlet {
	private static final String ATTR_ACAO = "acao";

	private static final long serialVersionUID = 1L;
	
	private String jsp = "";
	
    public RJxController() {
        super();
    }

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String acao = request.getParameter(ATTR_ACAO);
		
		if(acao == null) gerarErro(Erro.FALTA_PARAMETROS, request, response);
		else{
			
			if(acao.equals(Acao.LOGIN) || acao.equals(Acao.SAIR)){
				jsp = LoginController.execute(request, acao);
			}
			else if(acao.equals(Acao.CRIAR_NOVA_CONTA)){
				jsp = CriarContaController.execute(request);
			}
			else if(acao.equals(Acao.ACESSAR_CRIAR_NOVA_CONTA)){
				jsp = Forward.ACESSAR_CRIAR_NOVA_CONTA;
			}
			else if(acao.equals(Acao.PESQUISAR)){
				jsp = PesquisaController.execute(request);
			}
			else if(acao.equals(Acao.VER_PRODUTO) || acao.equals(Acao.ADICIONAR_NO_CARRINHO)){
				jsp = ProdutoController.execute(request, acao);
			}
			else if(acao.equals(Acao.VER_CARRINHO)){
				jsp = CarrinhoController.execute(request);
			}
		
			
			redirecionar(request, response);
		}
 	}

	private void gerarErro(String msg, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("erro", msg);
		jsp = Forward.ERRO;
		redirecionar(request, response);
	}

	private void redirecionar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher rd = request.getRequestDispatcher(jsp);
		rd.forward(request, response);
	}
}
